package com.fh.controller.building.contract;

import com.fh.controller.base.BaseController;
import com.fh.controller.system.tools.GetDatalayui;
import com.fh.controller.system.tools.PushToApp;
import com.fh.controller.system.tools.errorutils;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.attachment.AttachmentService;
import com.fh.service.building.RecordService;
import com.fh.service.building.contract.ContractService;
import com.fh.service.building.contract.LoanService;
import com.fh.service.building.customer.CustomerService;
import com.fh.service.building.message.SysMessageService;
import com.fh.service.hydropower.HydropowerService;
import com.fh.service.role.ShsRoleService;
import com.fh.service.system.user.UserService;
import com.fh.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 * Created by caozengling on 2018年7月2日.
 */
@Controller
@RequestMapping(value = "/LoanController")
public class LoanController extends BaseController {
    @Resource(name = "contractService")
    private ContractService contractService;
    @Resource(name = "loanService")
    private LoanService loanService;
    @Resource(name = "hydropowerService")
    private HydropowerService hydropowerService;
    @Resource(name = "attachmentService")
    private AttachmentService attachmentService;
    @Resource(name = "recordService")
    private RecordService recordService;
    @Resource(name = "sysMessageService")
    private SysMessageService sysMessageService;
    @Resource(name = "shsRoleService")
    private ShsRoleService roleService;
    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "customerService")
    private CustomerService customerService;
    @Resource
    private PlatformTransactionManager transactionManager;


    /**
     * 审批事项
     * 新建中的业务
     */
    @RequestMapping(value = "/contractshenpi")
    @ResponseBody
    public Object contractshenpi(Page page) throws Exception {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;


        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            PageData dataAuth = roleService.authListByLoginUser(pd);
            if(null!=dataAuth){
                String dataStr = "(";
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_1") != -1) {
                    //一级权限
                    dataStr += "\"0\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_2") != -1) {
                    //二级权限
                    dataStr += "\"3\",";//复审的时候 有2个人 所以暂时设置2
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_3") != -1) {
                    //三级权限
                    dataStr += "\"5\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_4") != -1) {
                    //四级权限
                    dataStr += "\"7\",";
                }
                dataStr += "\"-1\")";
                pd.put("CHECK_STATE", dataStr);
            }
            getPData(page, pd);
            varList = loanService.contractshenpi(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }
    /**
     * 业务管理
     * 审批中的业务
     */
    @RequestMapping(value = "/contractBuss")
    @ResponseBody
    public Object contractBuss(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
            }
            getPData(page, pd);
            varList = loanService.contractBuss(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 业务管理
     * 已完成的 业务
     */
    @RequestMapping(value = "/contractBussYes")
    @ResponseBody
    public Object contractBussYes(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
            }
            getPData(page, pd);
            varList = loanService.contractBussYes(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 业务管理
     * 作废的 业务
     */
    @RequestMapping(value = "/contractBussInvalid")
    @ResponseBody
    public Object contractBussInvalid(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
            }
            getPData(page, pd);
            varList = loanService.contractBussInvalid(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 业务管理
     * 暂存的
     */
    @RequestMapping(value = "/contractZancun")
    @ResponseBody
    public Object contractZancun(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
            }
            getPData(page, pd);
            varList = loanService.contractBussZancun(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 进行中的贷款合同
     */
    @RequestMapping(value = "/contracting")
    @ResponseBody
    public Object contracting(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
            }
            getPData(page, pd);
            varList = loanService.listcontracting(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 进行中的贷款合同
     */
    @RequestMapping(value = "/contractend")
    @ResponseBody
    public Object contractend(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
            }
            getPData(page, pd);
            varList = loanService.contractend(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 将到期的贷款合同
     */
    @RequestMapping(value = "/contractwill")
    @ResponseBody
    public Object contractwill(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
            }
            pd.put("CON_END_DATE", DateUtil.getAfterDayDate("90"));
            getPData(page, pd);
            varList = loanService.contractwill(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 贷款租客 数据展示（json）
     */
    @RequestMapping(value = "/zhlist")
    @ResponseBody
    public Object zhlist(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            //测试分页 导出为layui的json数据
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            String e_price="";
            pd.put("e_price",e_price);
            if(!"".equals(pd.getString("loan_price"))&&null!=pd.getString("loan_price")){
                String loan_price=pd.get("loan_price").toString();
                //分解 贷款数
                String price[] = loan_price.split("-");
                if(price.length>1){
                    String s_price=price[0].replace("w","0000");
                    e_price=price[1].replace("w","0000");
                    pd.put("s_price",s_price);
                    pd.put("e_price",e_price);
                }else {
                    e_price=price[0].substring(0, price[0].indexOf("w"));
                    pd.put("s_price",e_price+"0000");
                }

            }
            pd.put("TEN_TYPE",1);//0合同 1 贷款租户
            getPData(page, pd);//必填 2参
            varList = loanService.zhlist(page);    //列出Building列表
            datalayui = getLData(page, varList);//必填 2参
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 首页代办数目
     *
     * @return
     */
    @RequestMapping(value = "/initmsg")
    @ResponseBody
    public Object initmsg() {
        logBefore(logger, "获取首页代办数目");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            Page page =new Page();
            pd.put("USER_ID", user.getUSER_ID());
            pd.put("limit",999999999);
            pd.put("page",999999999);
            PageData dataAuth = roleService.authListByLoginUser(pd);
            if(null!=dataAuth){
                String dataStr = "(";
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_1") != -1) {
                    //一级权限
                    dataStr += "\"0\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_2") != -1) {
                    //二级权限
                    dataStr += "\"3\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_3") != -1) {
                    //三级权限
                    dataStr += "\"5\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_4") != -1) {
                    //四级权限
                    dataStr += "\"7\",";
                }
                dataStr += "\"-1\")";
                pd.put("CHECK_STATE", dataStr);
            }
            getPData(page, pd);
            List<PageData> varList = loanService.contractshenpi(page);
            resultPd.put("data", varList);
            resultPd.put("errcode", "0");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    /**
     * 首页租户列表和数据 获取贷款合同详情
     *
     * @return
     */
    @RequestMapping(value = "/findloaninfo")
    @ResponseBody
    public Object findloaninfo() {
        logBefore(logger, "获取贷款合同详情");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> contract = loanService.find_loan_info(pd);
            resultPd.put("data", contract);
            resultPd.put("errcode", "0");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    /****************************** 账单 ****************************************/

    /**
     * 返回list 账单 未付款 列表
     */
    @RequestMapping(value = "/yingshouList")
    @ResponseBody
    public Object yingshouList(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());

            String e_price="";
            pd.put("e_price",e_price);
            if(!"".equals(pd.getString("loan_price"))&&null!=pd.getString("loan_price")){
                String loan_price=pd.get("loan_price").toString();
                //分解 贷款数
                String price[] = loan_price.split("-");
                if(price.length>1){
                    String s_price=price[0].replace("w","0000");
                    e_price=price[1].replace("w","0000");
                    pd.put("s_price",s_price);
                    pd.put("e_price",e_price);
                }else {
                    e_price=price[0].substring(0, price[0].indexOf("w"));
                    pd.put("s_price",e_price+"0000");
                }

            }
            getPData(page, pd);
            varList = loanService.yingshouList(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 返回list 账单 已收 列表
     */
    @RequestMapping(value = "/yishouList")
    @ResponseBody
    public Object yishouList(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            String e_price="";
            pd.put("e_price",e_price);
            if(!"".equals(pd.getString("loan_price"))&&null!=pd.getString("loan_price")){
                String loan_price=pd.get("loan_price").toString();
                //分解 贷款数
                String price[] = loan_price.split("-");
                if(price.length>1){
                    String s_price=price[0].replace("w","0000");
                    e_price=price[1].replace("w","0000");
                    pd.put("s_price",s_price);
                    pd.put("e_price",e_price);
                }else {
                    e_price=price[0].substring(0, price[0].indexOf("w"));
                    pd.put("s_price",e_price+"0000");
                }

            }
            getPData(page, pd);
            varList = loanService.yishouList(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 返回list 账单 流水明细 收入
     */
    @RequestMapping(value = "/lsmxshouru")
    @ResponseBody
    public Object lsmxshouru(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            String e_price="";
            pd.put("e_price",e_price);
            if(!"".equals(pd.getString("loan_price"))&&null!=pd.getString("loan_price")){
                String loan_price=pd.get("loan_price").toString();
                //分解 贷款数
                String price[] = loan_price.split("-");
                if(price.length>1){
                    String s_price=price[0].replace("w","0000");
                    e_price=price[1].replace("w","0000");
                    pd.put("s_price",s_price);
                    pd.put("e_price",e_price);
                }else {
                    e_price=price[0].substring(0, price[0].indexOf("w"));
                    pd.put("s_price",e_price+"0000");
                }

            }
            pd.put("PRICE_TYPE",0);
            getPData(page, pd);
            varList = loanService.lsmxshouru(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 返回list 账单 流水明细 收入
     */
    @RequestMapping(value = "/lsmxzhichu")
    @ResponseBody
    public Object lsmxzhichu(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            String e_price="";
            pd.put("e_price",e_price);
            if(!"".equals(pd.getString("loan_price"))&&null!=pd.getString("loan_price")){
                String loan_price=pd.get("loan_price").toString();
                //分解 贷款数
                String price[] = loan_price.split("-");
                if(price.length>1){
                    String s_price=price[0].replace("w","0000");
                    e_price=price[1].replace("w","0000");
                    pd.put("s_price",s_price);
                    pd.put("e_price",e_price);
                }else {
                    e_price=price[0].substring(0, price[0].indexOf("w"));
                    pd.put("s_price",e_price+"0000");
                }

            }
            pd.put("PRICE_TYPE",1);
            getPData(page, pd);
            varList = loanService.lsmxzhichu(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


    /**
     * 返回  贷款首页 总收入
     */
    @RequestMapping(value = "/totalRevenue")
    @ResponseBody
    public PageData totalRevenue() {
        logBefore(logger, "贷款首页 总收入");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            PageData data = new PageData();
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> listdata = loanService.totalRevenue(pd);
            res.put("data", listdata);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", "内部错误");
        }

        return res;
    }


    /****************************** 合同 ****************************************/

    /**
     * 新增--保存贷款业务
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() {
       /* DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);*/

        logBefore(logger, "保存贷款合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        String contractId = this.get32UUID();

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");
            JSONArray BILL = (JSONArray) map2.get("BILL");
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");
            JSONObject financial = (JSONObject) map2.get("financial");//财务信息
            String LOAN_ID = (String) map2.get("LOAN_ID");//产业id
            String tenantId = this.get32UUID();
            String financialId = this.get32UUID();//财务信息


                if(StringUtils.isBlank(CONTRACT.getString("ID"))){
                    // 保存租户信息
                    if (TENANT != null && !TENANT.equals("")) {
                        PageData pd = new PageData();
                        pd.put("ID", tenantId);    //主键
                        pd.put("IS_DEL", 1); //是否删除
                        pd.put("SORT", 0); //排序
                        pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                        pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        pd.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));
                        pd.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));
                        pd.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));
                        pd.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));
                        pd.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));
                        pd.put("CONTRACT_ADDRESS", TENANT.get("CONTRACT_ADDRESS"));
                        pd.put("BYNAME", TENANT.get("BYNAME"));
                        pd.put("COMPANY_TYPE", TENANT.get("COMPANY_TYPE"));
                        pd.put("REG_CAPITAL", TENANT.get("REG_CAPITAL"));
                        pd.put("REG_CAPITAL_PAY", TENANT.get("REG_CAPITAL_PAY"));
                        pd.put("ESTABLISH_DATE", TENANT.get("ESTABLISH_DATE"));
                        pd.put("REG_ADDRESS", TENANT.get("REG_ADDRESS"));
                        pd.put("BUSINESS_ADDRESS", TENANT.get("BUSINESS_ADDRESS"));
                        pd.put("TEN_TYPE", 1);//0合同租户 1贷款租户
                        contractService.saveTenant(pd);
                    }
                    // 保存合同信息
                    if (CONTRACT != null && !CONTRACT.equals("")) {
                        PageData pd = new PageData();
                        pd.put("ID", contractId);    //主键
                        pd.put("IS_DEL", 0); //是否删除
                        pd.put("SORT", 0); //排序
                        pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                        pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                        pd.put("UPDATE_DATE", new DateUtil().getTime());
                        pd.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                        pd.put("PERSON_ID", tenantId);
                        pd.put("CREATE_TIME", new DateUtil().getTime());
                        pd.put("CUSTOMER_ID", tenantId);
                        pd.put("SIGNER", CONTRACT.get("SIGNER"));
                        pd.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                        pd.put("CHECK_STATE", "0");//初审待审核
                        pd.put("STATE", CONTRACT.get("STATE"));
                        pd.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                        pd.put("LOAN_PRICE", CONTRACT.get("LOAN_PRICE"));//借款金额
                        pd.put("TRNANTRY", CONTRACT.get("TRNANTRY"));//借款金额
                        pd.put("BORROW_INTEREST_RATE", CONTRACT.get("BORROW_INTEREST_RATE"));//借款利率
                        pd.put("BORROW_PERIOD", CONTRACT.get("BORROW_PERIOD"));//借款期限
                        pd.put("LATE_FEE", CONTRACT.get("late_fee"));//滞纳金
                        pd.put("REPAYMENT", CONTRACT.get("repayment"));//还款方式
                        pd.put("PREPAYDAYS", CONTRACT.get("prePayDays"));//付息日期（提前n天 固定几号）
                        pd.put("PAYMENT_REMINDER_DAY", CONTRACT.get("payment_reminder_day"));//付款日期提前天数/每月固定日期
                        pd.put("LATE_PAYMENT_RATE", CONTRACT.get("LATE_PAYMENT_RATE"));//滞纳金比率
                        pd.put("LATE_PAY_DATE", CONTRACT.get("late_pay_date"));//滞纳金执行日：收费日后
                        pd.put("CON_TEN_DATE", CONTRACT.get("CON_TEN_DATE"));
                        pd.put("CON_DATE", CONTRACT.get("CON_DATE"));
                        pd.put("CON_HR_DATE", CONTRACT.get("CON_HR_DATE"));
                        pd.put("CON_END_DATE", CONTRACT.get("CON_END_DATE"));
                        pd.put("WARN_TO_DATE", CONTRACT.get("WARN_TO_DATE"));
                        pd.put("CONTRACT_NUM", CONTRACT.get("CONTRACT_NUM"));
                        pd.put("INFO", CONTRACT.get("INFO"));

                        pd.put("LENDER", CONTRACT.get("LENDER"));
                        loanService.saveContract(pd);



                        if(StringUtils.isNoneBlank(LOAN_ID)){
                            PageData pageData = new PageData();
                            pageData.put("LOAN_ID",LOAN_ID);
                            pageData.put("LOAN_ID_NEW",contractId);
                            loanService.editAllLOAN(pageData);
                        }
                    }

                    //保存财务信息
                    if (financial.size() > 0) {
                        PageData pd = new PageData();
                        pd.put("ID", financialId);    //主键
                        pd.put("IS_DEL", 0); //是否删除
                        pd.put("SORT", 0); //排序
                        pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                        pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                        pd.put("UPDATE_DATE", new DateUtil().getTime());
                        pd.put("ASSET_LIABILITY",financial.get("ASSET_LIABILITY"));
                        pd.put("LIQUIDITY",financial.get("LIQUIDITY"));
                        pd.put("QUICK_RATIO",financial.get("QUICK_RATIO"));
                        pd.put("PROFIT",financial.get("PROFIT"));
                        pd.put("DATA_START",financial.get("DATA_START"));
                        pd.put("DATA_END",financial.get("DATA_END"));
                        pd.put("CONTRACT_ID",contractId);

                        pd.put("STOCK",financial.get("STOCK"));
                        pd.put("CURRENT_ASSETS",financial.get("CURRENT_ASSETS"));
                        pd.put("TOTAL_ASSETS",financial.get("TOTAL_ASSETS"));
                        pd.put("CURRENT_LIABILITIES",financial.get("CURRENT_LIABILITIES"));
                        pd.put("TOTAL_LIABILITIES",financial.get("TOTAL_LIABILITIES"));
                        pd.put("OWNERSHIP",financial.get("OWNERSHIP"));
                        pd.put("MAIN_BUSINESS_IN",financial.get("MAIN_BUSINESS_IN"));
                        pd.put("PROFIT_TOTAL",financial.get("PROFIT_TOTAL"));
                        loanService.savefinancial(pd);

                    }

//            保存附件信息
                    if (null!=ATTACHMENT&&ATTACHMENT.size() > 0) {
                        for (int i = 0; i < ATTACHMENT.size(); i++) {
                            PageData pd = new PageData();
                            JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                            pd.put("ID", this.get32UUID());    //主键
                            pd.put("OID", contractId);
                            pd.put("NAME", jo.get("name"));
                            pd.put("ATT_TYPE", jo.get("ATT_TYPE"));
                            pd.put("SIZE", jo.get("size"));
                            pd.put("EXT", jo.get("ext"));
                            pd.put("PATH", jo.get("url"));
                            pd.put("TYPE", jo.get("TYPE"));
                            pd.put("SORT", i + 1);
                            pd.put("REMARK", "");
                            pd.put("CREATE_TIME", new DateUtil().getTime());
                            pd.put("CREATE_ID", user.getUSER_ID());
                            pd.put("IS_DELETED", 0);
                            attachmentService.saveAttachment(pd);
                        }
                    }

//            保存联系人信息
                    if (CONTACTS.size() > 0) {
                        for (int i = 0; i < CONTACTS.size(); i++) {
                            PageData pd = new PageData();
                            JSONObject jo = (JSONObject) CONTACTS.get(i);
                            pd.put("ID", this.get32UUID());    //主键
                            pd.put("CONTRACT_ID", contractId);
                            pd.put("CONTACTS_NAME", jo.get("CONTACTS_NAME"));
                            pd.put("CONTACTS_TEL", jo.get("CONTACTS_TEL"));
                            contractService.saveContacts(pd);
                        }
                    }
//

                    //保存操作记录
                    PageData oppd = new PageData();
                    oppd.put("ID", this.get32UUID());    //主键
                    oppd.put("IS_DEL", 0); //是否删除
                    oppd.put("SORT", 0); //排序
                    oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                    oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
                    oppd.put("DETAILS", "创建合同，提交审核");//提交合同
                    oppd.put("CONTRACT_ID", contractId);
                    oppd.put("OPERATOR", user.getNAME());
//            recordService.save(oppd);
                    res.put("data", "");
                    res.put("errcode", "0");
                    res.put("errmsg", "ok");
                  //  transactionManager.commit(status);

                }else{
                    //修改

                    PageData pdCont = new PageData();
                    pdCont.put("ID", CONTRACT.get("ID"));//
                    pdCont.put("TRNANTRY", CONTRACT.get("TRNANTRY"));//0公司  1 个人  出借方
                    pdCont.put("SIGNER", CONTRACT.get("SIGNER"));//签订人
                    pdCont.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));//签订人 联系电话
                    pdCont.put("LENDER", CONTRACT.get("LENDER"));
                    loanService.uodateToloan(pdCont);
                    PageData pdTenant = new PageData();
                    pdTenant.put("ID", TENANT.get("PERSON_ID"));//
                    pdTenant.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));//公司名
                    pdTenant.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));//统一社会信用代码
                    pdTenant.put("ESTABLISH_DATE", TENANT.get("ESTABLISH_DATE"));//成立日期
                    pdTenant.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));//行业类别
                    pdTenant.put("COMPANY_TYPE", TENANT.get("COMPANY_TYPE"));//公司类型
                    pdTenant.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));//法人
                    pdTenant.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));//法人  联系电话
                    pdTenant.put("REG_CAPITAL", TENANT.get("REG_CAPITAL"));//注册资金(认缴)
                    pdTenant.put("REG_CAPITAL_PAY", TENANT.get("REG_CAPITAL_PAY"));//注册资金(实缴)
                    pdTenant.put("REG_ADDRESS", TENANT.get("REG_ADDRESS"));//注册地址
                    pdTenant.put("BUSINESS_ADDRESS", TENANT.get("BUSINESS_ADDRESS"));//经营地址
                    contractService.updateTenant(pdTenant);
                    res.put("data", "");
                    res.put("errcode", "0");
                    res.put("errmsg", "ok");
                }





        } catch (Exception e) {
            //transactionManager.rollback(status);
            logger.error(e.toString(), e);
            PageData pd = new PageData();
            pd.put("id", contractId);
            try {
                loanService.delContract(pd);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 新增--生成贷款业务
     */
    @RequestMapping(value = "/updateloan")
    @ResponseBody
    public PageData updateloan() {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);

        logBefore(logger, "生成贷款合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");//租户信息
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");//合同信息
            JSONArray BILL = (JSONArray) map2.get("BILL");//账单信息
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");


            // 对业务生成的 租户信息进行 正式入库
            if (TENANT != null && !TENANT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", TENANT.get("PERSON_ID"));//
                pd.put("IS_DEL", "0"); //是否删除
                contractService.updateTenant(pd);
            }
            // 保存合同信息
            if (CONTRACT != null && !CONTRACT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", CONTRACT.get("UP_ID"));    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                pd.put("UPDATE_DATE", new DateUtil().getTime());
                pd.put("STATE", "1");//进入合同期
                pd.put("CHECK_STATE", "1");//进入合同期
                pd.put("CONTRACT_NUM", CONTRACT.get("CONTRACT_NUM"));
                pd.put("CON_DATE", CONTRACT.get("CON_DATE"));
                pd.put("CON_HR_DATE", CONTRACT.get("CON_HR_DATE"));
                pd.put("CON_END_DATE", CONTRACT.get("CON_END_DATE"));
                pd.put("INFO", CONTRACT.get("INFO"));
                loanService.checkloan(pd);


            }

//            保存附件信息
            if (null!=ATTACHMENT&&ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("OID", CONTRACT.get("UP_ID"));
                    pd.put("NAME", jo.get("name"));
                    pd.put("SIZE", jo.get("size"));
                    pd.put("EXT", jo.get("ext"));
                    pd.put("PATH", jo.get("url"));
                    pd.put("TYPE", "contract");
                    pd.put("SORT", i + 1);
                    pd.put("REMARK", "");
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
//                    attachmentService.saveAttachment(pd);
                }
            }


//            保存账单信息
            if (BILL.size() > 0) {
                for (int i = 0; i < BILL.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BILL.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("IS_DEL", 0); //是否删除
                    pd.put("SORT", jo.get("SORT")); //排序
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建人ID
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", CONTRACT.get("UP_ID"));
                    pd.put("TENANT_ID",CONTRACT.get("PERSON_ID"));
                    pd.put("START_DATE", jo.get("START_DATE"));
                    pd.put("END_DATE", jo.get("END_DATE"));
                    pd.put("PAY_DATE", jo.get("PAY_DATE"));
                    pd.put("TOTAL_PRICE", jo.get("PRICE"));
                    pd.put("BILL_TYPE", jo.get("BILL_TYPE"));
                    pd.put("BILL_NAME", jo.get("BILL_NAME"));
                    pd.put("STATE", jo.get("STATE"));
                    pd.put("ACT_PAY_DATE", jo.get("ACT_PAY_DATE"));
                    pd.put("INFO", jo.get("INFO"));
                    pd.put("PROPERTY_ID", jo.get("PROPERTY_ID"));
                    pd.put("PAY_TYPE", "");
                    pd.put("PAY_TYPE_PROPORTION", "");
                    pd.put("PAY_TYPE_MONEY", "");
                    pd.put("MAKE_BILL_TYPE", jo.get("MAKE_BILL_TYPE"));
                    pd.put("ALLOT_BILL", jo.get("ALLOT_BILL"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    pd.put("CHECK_STATE", 1);//默认通过
                    pd.put("BILL_STATE", jo.get("BILL_STATE"));
                    contractService.saveBill(pd);
                }
            }
            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "创建合同，提交审核");//提交合同
            oppd.put("CONTRACT_ID", CONTRACT.get("UP_ID"));
            oppd.put("OPERATOR", user.getNAME());
//            recordService.save(oppd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 被驳回 再次提交
     */
    @RequestMapping(value = "/updateAgain")
    @ResponseBody
    public PageData updateAgain() {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);

        logBefore(logger, "生成贷款合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");//租户信息
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");//合同信息
            JSONArray BILL = (JSONArray) map2.get("BILL");//账单信息
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");
            JSONObject financial = (JSONObject) map2.get("financial");//财务信息

            // 对业务生成的 租户信息进行修改
            if (TENANT != null && !TENANT.equals("")) {
                PageData pdTENANT = new PageData();
                pdTENANT.put("ID", TENANT.get("PERSON_ID"));//
                pdTENANT.put("SORT", 0); //排序
                pdTENANT.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pdTENANT.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pdTENANT.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));
                pdTENANT.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));
                pdTENANT.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));
                pdTENANT.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));
                pdTENANT.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));
                pdTENANT.put("CONTRACT_ADDRESS", TENANT.get("CONTRACT_ADDRESS"));
                pdTENANT.put("BYNAME", TENANT.get("BYNAME"));
                pdTENANT.put("COMPANY_TYPE", TENANT.get("COMPANY_TYPE"));
                pdTENANT.put("REG_CAPITAL", TENANT.get("REG_CAPITAL"));
                pdTENANT.put("REG_CAPITAL_PAY", TENANT.get("REG_CAPITAL_PAY"));
                pdTENANT.put("ESTABLISH_DATE", TENANT.get("ESTABLISH_DATE"));
                pdTENANT.put("REG_ADDRESS", TENANT.get("REG_ADDRESS"));
                pdTENANT.put("BUSINESS_ADDRESS", TENANT.get("BUSINESS_ADDRESS"));
                pdTENANT.put("TEN_TYPE", 1);//0合同租户 1贷款租户
                contractService.updateTenant(pdTENANT);
            }
            // 保存合同信息
            if (CONTRACT != null && !CONTRACT.equals("")) {
                PageData pdCONTRACT = new PageData();
                pdCONTRACT.put("ID", CONTRACT.get("ID"));    //主键
                pdCONTRACT.put("IS_DEL", 0); //是否删除
                pdCONTRACT.put("SORT", 0); //排序
                pdCONTRACT.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pdCONTRACT.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pdCONTRACT.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                pdCONTRACT.put("UPDATE_DATE", new DateUtil().getTime());
                pdCONTRACT.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                pdCONTRACT.put("CREATE_TIME", new DateUtil().getTime());
                pdCONTRACT.put("SIGNER", CONTRACT.get("SIGNER"));
                pdCONTRACT.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                pdCONTRACT.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                pdCONTRACT.put("LOAN_PRICE", CONTRACT.get("LOAN_PRICE"));//借款金额 为了处理前台千分号返回
                pdCONTRACT.put("TRNANTRY", CONTRACT.get("TRNANTRY"));//0公司  1 个人
                pdCONTRACT.put("BORROW_INTEREST_RATE", CONTRACT.get("BORROW_INTEREST_RATE"));//借款利率
                pdCONTRACT.put("BORROW_PERIOD", CONTRACT.get("BORROW_PERIOD"));//借款期限
                pdCONTRACT.put("LATE_PAYMENT_RATE", CONTRACT.get("LATE_PAYMENT_RATE"));//滞纳金比率
                pdCONTRACT.put("INFO", CONTRACT.get("INFO"));
                pdCONTRACT.put("CHECK_STATE", "0");//被驳回都从初审开始审核
                loanService.checkloan(pdCONTRACT);
            }
            //保存财务信息
            if (financial.size() > 0) {
                PageData pd = new PageData();
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                pd.put("UPDATE_DATE", new DateUtil().getTime());
                pd.put("ASSET_LIABILITY",financial.get("ASSET_LIABILITY"));
                pd.put("LIQUIDITY",financial.get("LIQUIDITY"));
                pd.put("QUICK_RATIO",financial.get("QUICK_RATIO"));
                pd.put("PROFIT",financial.get("PROFIT"));
                pd.put("DATA_START",financial.get("DATA_START"));
                pd.put("DATA_END",financial.get("DATA_END"));
                pd.put("CONTRACT_ID",CONTRACT.get("ID"));

                pd.put("STOCK",financial.get("STOCK"));
                pd.put("CURRENT_ASSETS",financial.get("CURRENT_ASSETS"));
                pd.put("TOTAL_ASSETS",financial.get("TOTAL_ASSETS"));
                pd.put("CURRENT_LIABILITIES",financial.get("CURRENT_LIABILITIES"));
                pd.put("TOTAL_LIABILITIES",financial.get("TOTAL_LIABILITIES"));
                pd.put("OWNERSHIP",financial.get("OWNERSHIP"));
                pd.put("MAIN_BUSINESS_IN",financial.get("MAIN_BUSINESS_IN"));
                pd.put("PROFIT_TOTAL",financial.get("PROFIT_TOTAL"));
                loanService.updatefinancial(pd);
            }

//            保存附件信息
            if (null!=ATTACHMENT&&ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("OID", CONTRACT.get("ID"));
                    pd.put("NAME", jo.get("name"));
                    pd.put("SIZE", jo.get("size"));
                    pd.put("EXT", jo.get("ext"));
                    pd.put("PATH", jo.get("url"));
                    pd.put("TYPE", "contract");
                    pd.put("SORT", i + 1);
                    pd.put("REMARK", "");
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
//                    attachmentService.saveAttachment(pd);
                }
            }
            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "再次提交，提交审核");//提交合同
            oppd.put("CONTRACT_ID", CONTRACT.get("ID"));
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 暂存业务
     */
    @RequestMapping(value = "/zancun")
    @ResponseBody
    public PageData zancun() {
       /* DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);*/

        logBefore(logger, "暂存贷款合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        String contractId = this.get32UUID();

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");
            JSONArray BILL = (JSONArray) map2.get("BILL");
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");
            JSONObject financial = (JSONObject) map2.get("financial");//财务信息
            String LOAN_ID = (String) map2.get("LOAN_ID");//产业id



                String tenantId = this.get32UUID();
                String financialId = this.get32UUID();//财务信息
                // 保存租户信息
                if (TENANT != null && !TENANT.equals("")) {
                    PageData pd = new PageData();
                    pd.put("ID", tenantId);    //主键
                    pd.put("IS_DEL", 1); //是否删除
                    pd.put("SORT", 0); //排序
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));
                    pd.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));
                    pd.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));
                    pd.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));
                    pd.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));
                    pd.put("CONTRACT_ADDRESS", TENANT.get("CONTRACT_ADDRESS"));
                    pd.put("BYNAME", TENANT.get("BYNAME"));
                    pd.put("COMPANY_TYPE", TENANT.get("COMPANY_TYPE"));
                    pd.put("REG_CAPITAL", TENANT.get("REG_CAPITAL"));
                    pd.put("REG_CAPITAL_PAY", TENANT.get("REG_CAPITAL_PAY"));
                    pd.put("ESTABLISH_DATE", TENANT.get("ESTABLISH_DATE"));
                    pd.put("REG_ADDRESS", TENANT.get("REG_ADDRESS"));
                    pd.put("BUSINESS_ADDRESS", TENANT.get("BUSINESS_ADDRESS"));
                    pd.put("TEN_TYPE", 1);//0合同租户 1贷款租户
                    contractService.saveTenant(pd);
                }
                // 保存合同信息
                if (CONTRACT != null && !CONTRACT.equals("")) {
                    PageData pd = new PageData();
                    pd.put("ID", contractId);    //主键
                    pd.put("IS_DEL", 0); //是否删除
                    pd.put("SORT", 0); //排序
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                    pd.put("UPDATE_DATE", new DateUtil().getTime());
                    pd.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                    pd.put("PERSON_ID", tenantId);
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CUSTOMER_ID", tenantId);
                    pd.put("SIGNER", CONTRACT.get("SIGNER"));
                    pd.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                    pd.put("CHECK_STATE", "10");//暂存
                    pd.put("STATE", CONTRACT.get("STATE"));
                    pd.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                    pd.put("LOAN_PRICE", CONTRACT.get("LOAN_PRICE"));//借款金额
                    pd.put("TRNANTRY", CONTRACT.get("TRNANTRY"));//借款金额
                    pd.put("BORROW_INTEREST_RATE", CONTRACT.get("BORROW_INTEREST_RATE"));//借款利率
                    pd.put("BORROW_PERIOD", CONTRACT.get("BORROW_PERIOD"));//借款期限
                    pd.put("LATE_FEE", CONTRACT.get("late_fee"));//滞纳金
                    pd.put("REPAYMENT", CONTRACT.get("repayment"));//还款方式
                    pd.put("PREPAYDAYS", CONTRACT.get("prePayDays"));//付息日期（提前n天 固定几号）
                    pd.put("PAYMENT_REMINDER_DAY", CONTRACT.get("payment_reminder_day"));//付款日期提前天数/每月固定日期
                    pd.put("LATE_PAYMENT_RATE", CONTRACT.get("LATE_PAYMENT_RATE"));//滞纳金比率
                    pd.put("LATE_PAY_DATE", CONTRACT.get("late_pay_date"));//滞纳金执行日：收费日后
                    pd.put("CON_TEN_DATE", CONTRACT.get("CON_TEN_DATE"));
                    pd.put("CON_DATE", CONTRACT.get("CON_DATE"));
                    pd.put("CON_HR_DATE", CONTRACT.get("CON_HR_DATE"));
                    pd.put("CON_END_DATE", CONTRACT.get("CON_END_DATE"));
                    pd.put("WARN_TO_DATE", CONTRACT.get("WARN_TO_DATE"));
                    pd.put("INFO", CONTRACT.get("INFO"));


                    pd.put("LENDER", CONTRACT.get("LENDER"));
                    loanService.saveContract(pd);

                    if(StringUtils.isNoneBlank(LOAN_ID)){
                        PageData pageData = new PageData();
                        pageData.put("LOAN_ID",LOAN_ID);
                        pageData.put("LOAN_ID_NEW",contractId);
                        loanService.editAllLOAN(pageData);
                    }

                }

                //保存财务信息
                if (financial.size() > 0) {
                    PageData pd = new PageData();
                    pd.put("ID", financialId);    //主键
                    pd.put("IS_DEL", 0); //是否删除
                    pd.put("SORT", 0); //排序
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                    pd.put("UPDATE_DATE", new DateUtil().getTime());
                    pd.put("ASSET_LIABILITY",financial.get("ASSET_LIABILITY"));
                    pd.put("LIQUIDITY",financial.get("LIQUIDITY"));
                    pd.put("QUICK_RATIO",financial.get("QUICK_RATIO"));
                    pd.put("PROFIT",financial.get("PROFIT"));
                    pd.put("DATA_START",financial.get("DATA_START"));
                    pd.put("DATA_END",financial.get("DATA_END"));

                    pd.put("STOCK",financial.get("STOCK"));
                    pd.put("CURRENT_ASSETS",financial.get("CURRENT_ASSETS"));
                    pd.put("TOTAL_ASSETS",financial.get("TOTAL_ASSETS"));
                    pd.put("CURRENT_LIABILITIES",financial.get("CURRENT_LIABILITIES"));
                    pd.put("TOTAL_LIABILITIES",financial.get("TOTAL_LIABILITIES"));
                    pd.put("OWNERSHIP",financial.get("OWNERSHIP"));
                    pd.put("MAIN_BUSINESS_IN",financial.get("MAIN_BUSINESS_IN"));
                    pd.put("PROFIT_TOTAL",financial.get("PROFIT_TOTAL"));
                    pd.put("CONTRACT_ID",contractId);
                    loanService.savefinancial(pd);
                }

//            保存附件信息
                if (null!=ATTACHMENT&&ATTACHMENT.size() > 0) {
                    for (int i = 0; i < ATTACHMENT.size(); i++) {
                        PageData pd = new PageData();
                        JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                        pd.put("ID", this.get32UUID());    //主键
                        pd.put("OID", contractId);
                        pd.put("NAME", jo.get("name"));
                        pd.put("SIZE", jo.get("size"));
                        pd.put("EXT", jo.get("ext"));
                        pd.put("PATH", jo.get("url"));
                        pd.put("TYPE", jo.get("TYPE"));
                        pd.put("SORT", i + 1);
                        pd.put("REMARK", "");
                        pd.put("CREATE_TIME", new DateUtil().getTime());
                        pd.put("CREATE_ID", user.getUSER_ID());
                        pd.put("IS_DELETED", 0);
                        attachmentService.saveAttachment(pd);
                    }
                }

                //保存操作记录
                PageData oppd = new PageData();
                oppd.put("ID", this.get32UUID());    //主键
                oppd.put("IS_DEL", 0); //是否删除
                oppd.put("SORT", 0); //排序
                oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
                oppd.put("DETAILS", "创建合同，提交审核");//提交合同
                oppd.put("CONTRACT_ID", contractId);
                oppd.put("OPERATOR", user.getNAME());
//            recordService.save(oppd);
                res.put("data", "");
                res.put("errcode", "0");
                res.put("errmsg", "ok");



        } catch (Exception e) {
          //  transactionManager.rollback(status);
            logger.error(e.toString(), e);
            PageData pd = new PageData();
            pd.put("id", contractId);
            try {
                loanService.delContract(pd);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 暂存业务修改
     */
    @RequestMapping(value = "/zancunUpdate")
    @ResponseBody
    public PageData zancunUpdate() {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);

        logBefore(logger, "暂存修改贷款合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");//租户信息
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");//合同信息
            JSONArray BILL = (JSONArray) map2.get("BILL");//账单信息
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");
            JSONObject financial = (JSONObject) map2.get("financial");//财务信息

            // 对业务生成的 租户信息进行修改
            if (TENANT != null && !TENANT.equals("")) {
                PageData pdTENANT = new PageData();
                pdTENANT.put("ID", TENANT.get("PERSON_ID"));//
                pdTENANT.put("SORT", 0); //排序
                pdTENANT.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pdTENANT.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pdTENANT.put("INDUSTRY_ID", TENANT.getString("INDUSTRY_ID"));
                pdTENANT.put("COMPANY_NAME", TENANT.getString("COMPANY_NAME"));
                pdTENANT.put("BUSINESS_LICENSE", TENANT.getString("BUSINESS_LICENSE"));
                pdTENANT.put("LEGAL_PERSON_NAME", TENANT.getString("LEGAL_PERSON_NAME"));
                pdTENANT.put("LEGAL_PERSON_TEL", TENANT.getString("LEGAL_PERSON_TEL"));
//                pdTENANT.put("CONTRACT_ADDRESS", TENANT.getString("CONTRACT_ADDRESS"));
//                pdTENANT.put("BYNAME", TENANT.getString("BYNAME"));
                pdTENANT.put("COMPANY_TYPE", TENANT.getString("COMPANY_TYPE"));
                pdTENANT.put("REG_CAPITAL", TENANT.getString("REG_CAPITAL"));
                pdTENANT.put("REG_CAPITAL_PAY", TENANT.getString("REG_CAPITAL_PAY"));
                pdTENANT.put("ESTABLISH_DATE", TENANT.getString("ESTABLISH_DATE"));
                pdTENANT.put("REG_ADDRESS", TENANT.getString("REG_ADDRESS"));
                pdTENANT.put("BUSINESS_ADDRESS", TENANT.getString("BUSINESS_ADDRESS"));
                pdTENANT.put("TEN_TYPE", 1);//0合同租户 1贷款租户
                contractService.updateTenant(pdTENANT);
            }
            // 保存合同信息
            if (CONTRACT != null && !CONTRACT.equals("")) {
                PageData pdCONTRACT = new PageData();
                pdCONTRACT.put("ID", CONTRACT.get("ID"));    //主键
                pdCONTRACT.put("IS_DEL", 0); //是否删除
                pdCONTRACT.put("SORT", 0); //排序
                pdCONTRACT.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pdCONTRACT.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pdCONTRACT.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                pdCONTRACT.put("UPDATE_DATE", new DateUtil().getTime());
                pdCONTRACT.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                pdCONTRACT.put("CREATE_TIME", new DateUtil().getTime());
                pdCONTRACT.put("SIGNER", CONTRACT.get("SIGNER"));
                pdCONTRACT.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                pdCONTRACT.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                pdCONTRACT.put("LOAN_PRICE", CONTRACT.get("LOAN_PRICE"));//借款金额
                pdCONTRACT.put("TRNANTRY", CONTRACT.get("TRNANTRY"));//0公司  1 个人
                pdCONTRACT.put("BORROW_INTEREST_RATE", CONTRACT.get("BORROW_INTEREST_RATE"));//借款利率
                pdCONTRACT.put("BORROW_PERIOD", CONTRACT.get("BORROW_PERIOD"));//借款期限
                pdCONTRACT.put("LATE_PAYMENT_RATE", CONTRACT.get("LATE_PAYMENT_RATE"));//滞纳金比率
                pdCONTRACT.put("INFO", CONTRACT.get("INFO"));
                pdCONTRACT.put("CHECK_STATE", "10");//暂存
                loanService.checkloan(pdCONTRACT);
            }

            //保存财务信息
            if (financial.size() > 0) {
                PageData pd = new PageData();
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                pd.put("UPDATE_DATE", new DateUtil().getTime());
                pd.put("ASSET_LIABILITY",financial.get("ASSET_LIABILITY"));
                pd.put("LIQUIDITY",financial.get("LIQUIDITY"));
                pd.put("QUICK_RATIO",financial.get("QUICK_RATIO"));
                pd.put("PROFIT",financial.get("PROFIT"));
                pd.put("DATA_START",financial.get("DATA_START"));
                pd.put("DATA_END",financial.get("DATA_END"));
                pd.put("CONTRACT_ID",CONTRACT.get("ID"));

                pd.put("STOCK",financial.get("STOCK"));
                pd.put("CURRENT_ASSETS",financial.get("CURRENT_ASSETS"));
                pd.put("TOTAL_ASSETS",financial.get("TOTAL_ASSETS"));
                pd.put("CURRENT_LIABILITIES",financial.get("CURRENT_LIABILITIES"));
                pd.put("TOTAL_LIABILITIES",financial.get("TOTAL_LIABILITIES"));
                pd.put("OWNERSHIP",financial.get("OWNERSHIP"));
                pd.put("MAIN_BUSINESS_IN",financial.get("MAIN_BUSINESS_IN"));
                pd.put("PROFIT_TOTAL",financial.get("PROFIT_TOTAL"));
                loanService.savefinancial(pd);
            }
            PageData delpd = new PageData();
            delpd.put("OID",CONTRACT.get("ID"));
            attachmentService.realDeleteAttachmentByOid(delpd);//先进行删除

//            保存附件信息
            if (null!=ATTACHMENT&&ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    if(null!=ATTACHMENT.get(i)){
                        PageData pd = new PageData();
                        JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                            pd.put("ID", this.get32UUID());    //主键
                            pd.put("OID", CONTRACT.get("ID"));
                            pd.put("NAME", jo.get("name"));
                            pd.put("SIZE", jo.get("size"));
                            pd.put("EXT", jo.get("ext"));
                            pd.put("PATH", jo.get("url"));
                            pd.put("TYPE", jo.get("TYPE"));
                            pd.put("SORT", i + 1);
                            pd.put("REMARK", "");
                            pd.put("CREATE_TIME", new DateUtil().getTime());
                            pd.put("CREATE_ID", user.getUSER_ID());
                            pd.put("IS_DELETED", 0);
                            attachmentService.saveAttachment(pd);
                        }

                }
            }
            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "再次提交，提交审核");//提交合同
            oppd.put("CONTRACT_ID", CONTRACT.get("ID"));
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }


    /**
     * 根据合同ID获取合同详情信息
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData contractInfo() {
        logBefore(logger, "根据合同ID获取合同详情信息");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            PageData data = new PageData();
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> contract = loanService.find_loan_info(pd);
            List<PageData> contactData = contractService.findContactByContractId(pd);
            List<PageData> billData = contractService.findBillByContractId(pd);
            List<PageData> attachmentData = attachmentService.findByOId(pd);
            List<PageData> tb_financial = loanService.find_tb_financial(pd);//财务信息
            List<PageData> tb_loan_company = loanService.find_tb_loan_company(pd);//借款企业信息
            if(contract.size()>0){
                data.put("contract", contract.get(0));
            }
            if(tb_financial.size()>0){
                data.put("tb_financial", tb_financial.get(0));
            }
            if(tb_loan_company.size()>0){
                data.put("tb_loan_company", tb_loan_company.get(0));
            }
            data.put("contact", contactData);
            data.put("bill", billData);
            data.put("attachment", attachmentData);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", "内部错误");
        }

        return res;
    }

    /**
     * 终止合同
     */
    @RequestMapping(value = "/loanstop")
    @ResponseBody
    public PageData loanstop() {
        logBefore(logger, "终止贷款合同");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            PageData data = new PageData();
            pd.put("USER_ID", user.getUSER_ID());
            pd.put("UPDATE_DATE", new DateUtil().getTime());//合同的更新时间
            pd.put("UPDATE_ID", user.getUSER_ID());//合同变更者
            pd.put("STATE", 2);//终止
            //todo 终止合同 需要把还未收入的账单删除
            this.loanService.loanstop(pd);
            //删除终止合同的未收取的 账单
            this.loanService.del_loan_bill(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", "内部错误");
        }

        return res;
    }

    /**
     * 终止合同
     */
    @RequestMapping(value = "/loanzuofei")
    @ResponseBody
    public PageData loanzuofei() {
        logBefore(logger, "作废贷款合同");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            PageData data = new PageData();
            pd.put("USER_ID", user.getUSER_ID());
            pd.put("UPDATE_DATE", new DateUtil().getTime());//合同的更新时间
            pd.put("UPDATE_ID", user.getUSER_ID());//合同变更者
            pd.put("CHECK_STATE", 100);//作废
            //todo 终止合同 需要把还未收入的账单删除
            this.loanService.loanstop(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", "内部错误");
        }

        return res;
    }

    /**
     * pc审核
     *
     * @return
     */
    @RequestMapping(value = "/checkloan")
    @ResponseBody
    public Object checkloan() {
        logBefore(logger, "审核贷款");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            PageData oppd = new PageData();
            List<PageData> list2 = (List<PageData>) JSONArray.toList(JSONArray.fromObject(pd.getString("ATTACHMENT")), PageData.class);
            List<PageData> CONTACTS = (List<PageData>) JSONArray.toList(JSONArray.fromObject(pd.getString("CONTACTS")), PageData.class);//联系人数组
            Map<String, Object> CONTRACT=JSONHelper.json2Map(pd.getString("CONTRACT"));//合同信息
            Map<String, Object> TENANT=JSONHelper.json2Map(pd.getString("TENANT"));//租户信息
            Map<String, Object> tb_loan_company=JSONHelper.json2Map(pd.getString("loan_company"));//借款企业信息

            // 对业务生成的 租户信息进行修改
            if (TENANT != null && !TENANT.equals("")) {
                PageData pdTENANT = new PageData();
                pdTENANT.put("ID", TENANT.get("PERSON_ID"));//
                pdTENANT.put("SORT", 0); //排序
                pdTENANT.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pdTENANT.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pdTENANT.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));
                pdTENANT.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));
                pdTENANT.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));
                pdTENANT.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));
                pdTENANT.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));
                pdTENANT.put("CONTRACT_ADDRESS", TENANT.get("CONTRACT_ADDRESS"));
                pdTENANT.put("BYNAME", TENANT.get("BYNAME"));
                pdTENANT.put("COMPANY_TYPE", TENANT.get("COMPANY_TYPE"));
                pdTENANT.put("REG_CAPITAL", TENANT.get("REG_CAPITAL"));
                pdTENANT.put("REG_CAPITAL_PAY", TENANT.get("REG_CAPITAL_PAY"));
                pdTENANT.put("ESTABLISH_DATE", TENANT.get("ESTABLISH_DATE"));
                pdTENANT.put("REG_ADDRESS", TENANT.get("REG_ADDRESS"));
                pdTENANT.put("BUSINESS_ADDRESS", TENANT.get("BUSINESS_ADDRESS"));
                pdTENANT.put("TEN_TYPE", 1);//0合同租户 1贷款租户
                contractService.updateTenant(pdTENANT);
            }

            PageData pageData = new PageData();
            List<PageData> listuser = roleService.authListAllUser(pageData);//查询当前审核等级的人数
            int DY_CHECK_END=0;
            //todo 审核的时候带上审核人的标识 在审批列表区别
            // 保存合同信息
            if (null!=CONTRACT && !"".equals(CONTRACT)) {
                PageData pdCONTRACT = new PageData();
                pdCONTRACT.put("ID", pd.get("ID"));    //主键
                pdCONTRACT.put("IS_DEL", 0); //是否删除
                pdCONTRACT.put("SORT", 0); //排序
//                pdCONTRACT.put("CREATE_ID", user.getUSER_ID()); //创建用户
//                pdCONTRACT.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pdCONTRACT.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                pdCONTRACT.put("UPDATE_DATE", new DateUtil().getTime());
//                pdCONTRACT.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                pdCONTRACT.put("CREATE_TIME", new DateUtil().getTime());
                pdCONTRACT.put("SIGNER", CONTRACT.get("SIGNER"));
                pdCONTRACT.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                pdCONTRACT.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                pdCONTRACT.put("LOAN_PRICE", CONTRACT.get("LOAN_PRICE").toString().replace(",",""));//借款金额 为了处里 前台显示的千分号
                pdCONTRACT.put("TRNANTRY", CONTRACT.get("TRNANTRY"));//0公司  1 个人
                pdCONTRACT.put("BORROW_INTEREST_RATE", CONTRACT.get("BORROW_INTEREST_RATE"));//借款利率
                pdCONTRACT.put("BORROW_PERIOD", CONTRACT.get("BORROW_PERIOD"));//借款期限
                pdCONTRACT.put("LATE_PAYMENT_RATE", CONTRACT.get("LATE_PAYMENT_RATE"));//滞纳金比率
                pdCONTRACT.put("INFO", CONTRACT.get("INFO"));
                loanService.checkloan(pdCONTRACT);
            }

            pd.put("UPDATE_DATE", new DateUtil().getTime());//合同的更新时间
            pd.put("UPDATE_ID", user.getUSER_ID());//合同变更者
            if ("0".equals(pd.getString("CHECK"))) {//通过
                int check_num=0;//审核次数标识
                String DY_DY_CHECK="";
                List<String> result = Arrays.asList(CONTRACT.get("DY_CHECK").toString().split(","));
                switch (pd.getString("CHECK_STATE")){
                    case "初审阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "0");
                        if(result.size()==2){
                            for(PageData listusers:listuser){
                                if(null!=listusers.get("AUTH_CODE")){
                                    listusers.get("AUTH_CODE");
                                    if(listusers.get("AUTH_CODE").toString().indexOf("SHQX_1") != -1){
                                        DY_CHECK_END++;
                                    }
                                }
                            }
                            check_num=Integer.parseInt(result.get(0))+1;
                            DY_DY_CHECK=String.valueOf(check_num)+","+"1";
                            String DY_CHECK_NAM =CONTRACT.get("DY_CHECK_NAME").toString()+","+user.getUSER_ID()+",";//动态审核过的人
                            pd.put("DY_CHECK", DY_DY_CHECK);
                            pd.put("DY_CHECK_NAME", DY_CHECK_NAM);
                        }
                        if (DY_CHECK_END == check_num) {// 审核通过后的操作
                            pd.put("CHECK_STATE", "3");//初审阶段 进入复审
                            pd.put("DY_CHECK", "0,3");//0代办下一个阶段的开始 3 进入复审了
                            pd.put("DY_CHECK_NAME", "0");//清空审核人
                        }
                        //初审 借款企业信息入库
                        if (tb_loan_company != null && !tb_loan_company.equals("")) {
                            PageData loan_company = new PageData();
                            loan_company.put("ID", this.get32UUID());
                            loan_company.put("SORT", 0); //排序
                            loan_company.put("IS_DEL", 0); //排序
                            loan_company.put("CREATE_ID", user.getUSER_ID()); //创建用户
                            loan_company.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                            loan_company.put("HYYJ", tb_loan_company.get("HYYJ"));
                            loan_company.put("SHZTPJ", tb_loan_company.get("SHZTPJ"));
                            loan_company.put("SWPJ", tb_loan_company.get("SWPJ"));
                            loan_company.put("QYFX", tb_loan_company.get("QYFX"));
                            loan_company.put("QYZT", tb_loan_company.get("QYZT"));
                            loan_company.put("QSQK", tb_loan_company.get("QSQK"));
                            loan_company.put("QJSB", tb_loan_company.get("QJSB"));
                            loan_company.put("XZCFJL", tb_loan_company.get("XZCFJL"));
                            loan_company.put("FYSSXX", tb_loan_company.get("FYSSXX"));
                            loan_company.put("FYQZZX", tb_loan_company.get("FYQZZX"));
                            loan_company.put("DWDB", tb_loan_company.get("DWDB"));
                            loan_company.put("DWDBBL", tb_loan_company.get("DWDBBL"));
                            loan_company.put("YQDK", tb_loan_company.get("YQDK"));
                            loan_company.put("THYQDK", tb_loan_company.get("THYQDK"));
                            loan_company.put("DYWQSQX", tb_loan_company.get("DYWQSQX"));
                            loan_company.put("GLQYBL", tb_loan_company.get("GLQYBL"));
                            loan_company.put("CONTRACT_ID", pd.get("ID"));
                            loanService.saveTbLoanCompany(loan_company);
                        }
                        loanService.checkloan(pd);//审核合同
                        pd.put("DETAILS","初审通过,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        break;
                    case "复审阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "3");
                        //审核人标识+','+审核次数标志+","+阶段审核标志
                        if(result.size()==2){
                            for(PageData listusers:listuser){
                                if(null!=listusers.get("AUTH_CODE")){
                                    listusers.get("AUTH_CODE");
                                    if(listusers.get("AUTH_CODE").toString().indexOf("SHQX_2") != -1){
                                        DY_CHECK_END++;
                                    }
                                }
                            }
                            check_num=Integer.parseInt(result.get(0))+1;
                            DY_DY_CHECK=String.valueOf(check_num)+","+"3";
                            String DY_CHECK_NAM =CONTRACT.get("DY_CHECK_NAME").toString()+","+user.getUSER_ID()+",";//动态审核过的人
                            pd.put("DY_CHECK", DY_DY_CHECK);
                            pd.put("DY_CHECK_NAME", DY_CHECK_NAM);
                        }
                        if (DY_CHECK_END == check_num) {
                            pd.put("CHECK_STATE", "5");//复审阶段 进入终审阶段
                            pd.put("DY_CHECK", "0,5");//0代办下一个阶段的开始
                            pd.put("DY_CHECK_NAME", "0");//清空审核人
                        }
                        oppd.put("VISIT_CUSTOMER", pd.get("VISIT_CUSTOMER"));//约谈 下户
                        loanService.checkloan(pd);//审核合同
                        pd.put("DETAILS","复审通过,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        //复审附件
                        if (list2.size() > 0) {
                            for (PageData list : list2) {
                                PageData pds = new PageData();
                                pds.put("ID", this.get32UUID());    //主键
                                pds.put("OID", oppd.get("ID"));
                                pds.put("NAME", list.get("name"));
                                pds.put("EXT", list.get("ext"));
                                pds.put("PATH", list.get("url"));
                                pds.put("TYPE", 2);
                                pds.put("SORT", "1");
                                pds.put("REMARK", "复审阶段");
                                pds.put("CREATE_TIME", new DateUtil().getTime());
                                pds.put("CREATE_ID", user.getUSER_ID());
                                pds.put("IS_DELETED", 0);
                                attachmentService.saveAttachment(pds);
                            }
                        }
                        break;
                    case "终审阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "5");
                        if(result.size()==2){
                            for(PageData listusers:listuser){
                                if(null!=listusers.get("AUTH_CODE")){
                                    listusers.get("AUTH_CODE");
                                    if(listusers.get("AUTH_CODE").toString().indexOf("SHQX_3") != -1){
                                        DY_CHECK_END++;
                                    }
                                }
                            }
                            check_num=Integer.parseInt(result.get(0))+1;
                            DY_DY_CHECK=String.valueOf(check_num)+","+"5";
                            String DY_CHECK_NAM =CONTRACT.get("DY_CHECK_NAME").toString()+","+user.getUSER_ID()+",";//动态审核过的人
                            pd.put("DY_CHECK", DY_DY_CHECK);
                            pd.put("DY_CHECK_NAME",DY_CHECK_NAM);
                        }
                        if (DY_CHECK_END == check_num) {
                            pd.put("CHECK_STATE", "7");//终审阶段 进入合规阶段
                            pd.put("DY_CHECK", "0,7");//0代办下一个阶段的开始
                            pd.put("DY_CHECK_NAME", "0");//清空审核人
                        }
                        loanService.checkloan(pd);//审核合同
                        pd.put("DETAILS","终审通过,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        break;
                    case "合规阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "7");
                        if(result.size()==2){
                            for(PageData listusers:listuser){
                                if(null!=listusers.get("AUTH_CODE")){
                                    listusers.get("AUTH_CODE");
                                    if(listusers.get("AUTH_CODE").toString().indexOf("SHQX_4") != -1){
                                        DY_CHECK_END++;
                                    }
                                }
                            }
                            check_num=Integer.parseInt(result.get(0))+1;
                            DY_DY_CHECK=String.valueOf(check_num)+","+"7";
                            String DY_CHECK_NAM =CONTRACT.get("DY_CHECK_NAME").toString()+","+user.getUSER_ID()+",";//动态审核过的人
                            pd.put("DY_CHECK", DY_DY_CHECK);
                            pd.put("DY_CHECK_NAME", DY_CHECK_NAM);
                        }
                        if (DY_CHECK_END == check_num) {
                            pd.put("CHECK_STATE", "1");//进入
                        }
                        loanService.checkloan(pd);//审核合同
                        PageData pt=new PageData();//租户入库
                        pt.put("ID", TENANT.get("PERSON_ID"));
                        pt.put("IS_DEL", 0);
                        contractService.updateTenant(pt);
                        pd.put("DETAILS","合规通过,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        //复审附件
                        if (list2.size() > 0) {
                            for (PageData list : list2) {
                                PageData pds = new PageData();
                                pds.put("ID", this.get32UUID());    //主键
                                pds.put("OID", oppd.get("ID"));
                                pds.put("NAME", list.get("name"));
                                pds.put("EXT", list.get("ext"));
                                pds.put("PATH", list.get("url"));
                                pds.put("TYPE", 3);
                                pds.put("SORT", "1");
                                pds.put("REMARK", "合规阶段");
                                pds.put("CREATE_TIME", new DateUtil().getTime());
                                pds.put("CREATE_ID", user.getUSER_ID());
                                pds.put("IS_DELETED", 0);
                                attachmentService.saveAttachment(pds);
                            }
                        }
                        break;
                }
            } else if ("2".equals(pd.getString("CHECK"))) {//不通过
                switch (pd.getString("CHECK_STATE")){
                    case "初审阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "2");
                        loanService.checkloan(pd);
                        pd.put("DETAILS","初审驳回,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        break;
                    case "复审阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "4");
                        loanService.checkloan(pd);
                        pd.put("DETAILS","复审驳回,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        break;
                    case "终审阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "6");
                        pd.put("DETAILS","终审驳回,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        loanService.checkloan(pd);
                        break;
                    case "合规阶段":
                        pd.put("USER_ID", user.getUSER_ID());
                        pd.put("CHECK_STATE", "8");
                        pd.put("DETAILS","合规驳回,备注:"+pd.get("DETAILS"));
                        oppd.put("ID",this.get32UUID());
                        save_record(pd, user, oppd);
                        loanService.checkloan(pd);
                        break;
                }
            }
            resultPd.put("errcode", "0");
            resultPd.put("errmsg", "操作成功");
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }
    //保存操作记录
    private void save_record(PageData pd, User user, PageData oppd) throws Exception {
        oppd.put("ID", oppd.get("ID"));    //主键
        oppd.put("IS_DEL", 0); //是否删除
        oppd.put("SORT", 0); //排序
        oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
        oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
        oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
        oppd.put("CONTRACT_ID", pd.get("ID").toString());
        oppd.put("OPERATOR", user.getNAME());//审核人
        oppd.put("DETAILS", pd.get("DETAILS"));//审核意见
        recordService.save(oppd);
    }


    @RequestMapping(value = "/msg")
    public void sendMsgMeterReadingDay() throws Exception {
        PageData pd = new PageData();
        pd.put("type", "8");
        pd.put("phone",  "18500355622");
        pd.put("name", "czl");
//        SmsUtlis.sendSms(pd);

        //合同审批 短信通知
        PageData pageData = new PageData();
        List<PageData> authList = roleService.authListAllUser(pageData);
        for (PageData authLists:authList){
            PageData PD_USER = new PageData();
            PD_USER.put("USER_ID",authLists.get("USER_ID"));
            List<PageData> list = contractService.listcontractingShenHeMSG(PD_USER);
            if(list.size()>0){//有数据 说明有权限 给这个用户发送一条提醒
                PageData pdmsg = new PageData();
                pdmsg.put("type", "8");
                pdmsg.put("phone",  "18500355622");
                pdmsg.put("name", authLists.get("NAME"));
                //        SmsUtlis.sendSms(pdmsg);
            }
        }

        //合同审核
//        List<PageData> list = billService.findMeterReadingDay(pd);
//        for (PageData pdData : list) {
//            pageData.put("type", "8");
//            SmsUtlis.sendSms(pageData);
//        }

    }



    /**
     * 合同管理
     * 履约中
     */
    @RequestMapping(value = "/InCompliance")
    @ResponseBody
    public Object InCompliance( ) {

        PageData pd = this.getPageData();
        PageData res =new PageData();
        try {
            PageData  data= loanService.findInCompliance(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }



}
